package cn.tedu.four.ex.handler;

import cn.tedu.four.ex.ServiceException;
import cn.tedu.four.web.JsonResult;
import cn.tedu.four.web.ServiceCode;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

/**
 * ClassName: GlobalExceptionHandler
 * Package: cn.tedu.four.ex.handler
 * Description:
 *
 * @Author: @Albert
 * @Version: 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult handleService(ServiceException e){
        return JsonResult.fail(e);
    }
    @ExceptionHandler
    public String handleNull(NullPointerException e){
        return "空指针异常";
    }
    @ExceptionHandler
    public JsonResult handleBind(BindException e){
        System.out.println("正在处理BindException");
//        String suffix = "!";
//        String prefix = "提交相册失败:";
//        String delimiter = ",";
//        StringJoiner message = new StringJoiner(delimiter,prefix,suffix);
//        List<FieldError> fieldErrors = e.getFieldErrors();
//        for(FieldError fieldError:fieldErrors){
//            String defaultMessage = fieldError.getDefaultMessage();
//            message.add(defaultMessage);
//        }
        String message = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST, message.toString());
    }
    @ExceptionHandler
    public JsonResult handleCon(ConstraintViolationException e){
        System.out.println("正在处理+ConstraintViolationException ");
        StringBuilder message = null;
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for(ConstraintViolation<?> con:constraintViolations){
            message.append(con.getMessage());
        }

        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST, message.toString());
    }

}
